package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.util.concurrent.TimeUnit;

/**
* @author 28242
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-06-06 15:41:38
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    TbUserMapper tbUserMapper;

    @Override
    public Result login(LoginVo loginVo) {

        //判断验证码是否正确
        String key="login"+loginVo.getMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        if (redisCode==null){
            return Result.error().setMsg("验证码过期");
        }
        if (!loginVo.getCode().equals(redisCode)){
            return Result.error().setMsg("验证码错误");
        }

        TbUser tbUser = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginVo.getMobile())
        );
        if (tbUser==null){
            return Result.error().setMsg("用户不存在");
        }

        String rediskey="token-"+tbUser.getUserId();
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .compact();
        redisTemplate.opsForValue().set(rediskey,token,15,TimeUnit.MINUTES);

        tbUser.setToken(token);
        tbUser.setUserPass(null);



        return Result.ok().setData(tbUser);
    }

    @Override
    public Result sendCode(String mobile) {

        boolean mobile1 = Validator.isMobile(mobile);
        if (!mobile1){
            return Result.error().setMsg("手机号格式错误");
        }


        TbUser tbUser = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, mobile)
        );
        if (tbUser==null){
            tbUser = new TbUser();
            tbUser.setUserMobile(mobile);

            tbUser.readyCreated(null);

            tbUserMapper.insert(tbUser);
        }


        //生产验证码
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码为："+code);


        String key="login"+mobile;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);

        MobileMessageUtil.sendMobileMessage(mobile,code);

        return Result.ok();
    }
}




